import Vue from "vue";
import Vuex from "vuex";
import { auth, leave } from "@/apis";
import format from "@/utils/format";
import router from "@/router";
import { content, staticGeneral, staticPractise, staticViews } from "@/router";
import vuexPersist from "vuex-persistedstate";

Vue.use(Vuex);

const _userInfo = {
  username: null,
  nickname: "匿名用户",
  lastLoginTime: null,
};
/**
 *   {
    routeId: 5,
    name: "LeaveAudit",
    path: "/leaveAudit",
    component: "/views/hr/LeaveAudit",
    title: "—请假审核",
    icon: "el-icon-edit",
    level: 2,
    groupOrder: 2,
    parentId: 3,
    type: 1,
    pids: "3",
    comment: "请假业务中审核通过与不通过等",
  },

 {
    path: "/logon",
    name: "Logon",
    component: () => import("@/pages/Logon"),
  },
* */
function generateRoutesForRouter(routesFromDB) {
  let _routesFromDB = JSON.parse(JSON.stringify(routesFromDB));
  const r = _routesFromDB
    .filter((x) => x.type === 1)
    .map((x) => {
      return {
        path: x.path,
        name: x.name,
        //ok
        // component: () => import("@/views/" + x.component),
        //ok
        component: () => import("@/" + x.component),
        // bad  Cannot find module '@/views/hr/LeaveAudit
        // component: () => import("@" + x.component),
        // component: (resolve) => require([`@${x.component}`], resolve)
      };
    });
  console.log("=====格式化后的动态路由准备数据", r);
  return r;
}

function generateRoutesForNav(routesFromDB) {
  let _routesFromDB = JSON.parse(JSON.stringify(routesFromDB));
  //获取动态部分
  let dynamicViews = new format.Convert(_routesFromDB).convertToRootChildren();
  //统一格式化 如果需要加上静态部分
  //一般情况下是静态部分是开发人练习 可以只纳入路由体系不加入导航体系
  //在一般开发思路下 是先写静态纳入路由体系中开发，然后开发完毕后纳入导航体系

  return dynamicViews;
}
function generateRoutesForBread(routesFromDB) {
  let _routesFromDB = JSON.parse(JSON.stringify(routesFromDB));
  //如果需要再扩展
  return _routesFromDB;
}

export default new Vuex.Store({
  state: {
    userInfo: _userInfo,
    auth: false,
    collapse: true,
    dynamicRoutesAdd: false,
    leaveTypeEnums: [
      {
        index: 0,
        value: "sickLeave",
        text: "病假",
      },
      {
        index: 1,
        value: "annualLeave",
        text: "年假",
      },
    ],
    applyStateEnums: [
      {
        index: 0,
        value: "saved",
        text: "未提交",
      },
      {
        index: 1,
        value: "submitted",
        text: "已提交",
      },
    ],
    auditStateEnums: [
      {
        index: 0,
        value: "notAudit",
        text: "未审核",
      },
      {
        index: 1,
        value: "auditSucceeded",
        text: "审核通过",
      },
    ],
    departments: [
      {
        index: 0,
        value: "tech",
        text: "技术部",
      },
      {
        index: 1,
        value: "sale",
        text: "销售部",
      },
      {
        index: 2,
        value: "produce",
        text: "生产部",
      },
    ],
    operateStates: [
      {
        index: 0,
        value: "notSubmit",
        text: "未提交",
      },
      {
        index: 1,
        value: "notAudit",
        text: "未审核",
      },
      {
        index: 2,
        value: "audited",
        text: "已审核",
      },
    ],
    auditStates: [
      {
        index: 0,
        value: "NA",
        text: "尚未审计",
      },
      {
        index: 1,
        value: "auditSucceeded",
        text: "审计通过",
      },
      {
        index: 2,
        value: "auditFailed",
        text: "审计不过",
      },
    ],

    routesFromDB: [],
    routesForRouter: [],
    routesForNav: [],
    routesForBread: [],
    currentBreadList: ["某一级", "某二级"],
  },
  mutations: {
    updateCurrentBreadList(state, payload) {
      state.currentBreadList = payload;
    },
    sureDynamicRoutesAdd(state) {
      state.dynamicRoutesAdd = true;
    },
    updateRoutes(state, payload) {
      state.routesFromDB = payload;
      //todo：其他routes要根据routesFromBD作格式转化 以适配不同组件
      // state.routesForNav
      state.routesForRouter = generateRoutesForRouter(payload);
      state.routesForNav = generateRoutesForNav(payload);
      state.routesForBread = generateRoutesForBread(payload);
    },

    loginSuccess(state, payload) {
      state.userInfo = payload;
      state.auth = true;
    },
    logoutSuccess(state) {
      state.userInfo = _userInfo;
      state.auth = false;
    },
    updateLeaveTypeEnums(state, payload) {
      state.leaveTypeEnums = payload;
    },
    updateApplyStateEnums(state, payload) {
      state.applyStateEnums = payload;
    },
    updateAuditStateEnums(state, payload) {
      state.auditStateEnums = payload;
    },
    switchNav(state) {
      state.collapse = !state.collapse;
    },
  },
  actions: {
    getRoutesAll({ commit }) {
      // this.$http({
      //   method: "get",
      //   url: "http://localhost:9090/auth/route/supplyAll",
      // })
      return auth.getAllRoutes().then(
        (res) => {
          commit("updateRoutes", res.data);
          return undefined;
        },
        (error) => {
          console.log(" request error : " + error.response.status);
          return undefined;
        }
      );
    },
    getRoutesByCurrentUser({ commit }) {
      // return window.axios({
      //     method: "get",
      //     url: "http://localhost:9090/auth/route/supplyByUser",
      //   })
      return auth.getRoutesByCurrentUser().then(
        (res) => {
          commit("updateRoutes", res.data);
        },
        (error) => {
          console.log(" request error : " + error.response.status);
        }
      );
    },
    getLeaveTypeEnums({ commit }) {
      //return 封装
      /*window
        .axios({
          method: "get",
          url: "http://localhost:9091/leave/common/leaveTypes",
        })*/
      return leave.leaveTypes().then(
        (res) => {
          commit("updateLeaveTypeEnums", res.data);
        },
        (error) => {
          console.log(" request error : " + error.response.status);
        }
      );
    },
    getApplyStateEnums({ commit }) {
      // window
      //   .axios({
      //     method: "get",
      //     url: "http://localhost:9091/leave/common/applyStates",
      //   })
      return leave.applyStates().then(
        (res) => {
          commit("updateApplyStateEnums", res.data);
        },
        (error) => {
          console.log(" request error : " + error.response.status);
        }
      );
    },
    getAuditStateEnums({ commit }) {
      // window
      //   .axios({
      //     method: "get",
      //     url: "http://localhost:9091/leave/common/auditStates",
      //   })
      return leave.auditStates().then(
        (res) => {
          commit("updateAuditStateEnums", res.data);
        },
        (error) => {
          console.log(" request error : " + error.response.status);
        }
      );
    },
    //定义该函数为 用户初次登录成功后需要预先执行的业务初始化函数
    //也是 用户浏览器刷新页面后 需要执行的函数
    //也是 匿名用户初次登录成功后需要执行的业务函数
    appInit(store, getAll) {
      store.dispatch("getLeaveTypeEnums");
      store.dispatch("getApplyStateEnums");
      store.dispatch("getAuditStateEnums");
      const method = getAll ? "getRoutesAll" : "getRoutesByCurrentUser";
      return store.dispatch(method).then(() => {
        console.log("static", staticViews);
        console.log("dynamic", store.state.routesForRouter);
        //动静合并
        const c = [].concat(staticViews).concat(store.state.routesForRouter);
        content.children = c;
        router.addRoute(content);
        store.commit("sureDynamicRoutesAdd");
        console.log("=========所有路由 ", router.getRoutes());
      });
    },
  },
  modules: {},
  plugins: [
    vuexPersist({
      storage: window.sessionStorage,
      reducer: (state) => {
        return {
          userInfo: state.userInfo,
          auth: state.auth,
          collapse: state.collapse,
          currentBreadList: state.currentBreadList,
        };
      },
    }),
  ],
});
